package web.java.upload;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class Demo02_FileUpload extends HttpServlet {


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//1、文件上传工厂
		FileItemFactory factory=new DiskFileItemFactory();
		//2、创建文件上传核心工具类
		ServletFileUpload upload=new ServletFileUpload(factory);
		
		//一、设置单个文件允许的最大的大小
		upload.setFileSizeMax(30*1024*1024);
		//二、设置文件上传表单允许的总大小：80
		upload.setSizeMax(80*1014*1024);
		//三、设置上传表单文件名的编码	相当于 request.setCharacterEncoding("utf-8");
		upload.setHeaderEncoding("utf-8");
		
		//3、判断当前表单是否为文件上传表单
		if(upload.isMultipartContent(request)){
			//4、把请求数据转换成一个个FileItem对象，再用集合封装
			try {
				List<FileItem> list=upload.parseRequest(request);
				//遍历，得到每一个FileItem对象
				for(FileItem fileItem:list){
					//判断：文本数据
					if(fileItem.isFormField()){
						//普通文本数据
						String fieldName=fileItem.getFieldName();	//name
						String str=fileItem.getString();			//value 表单元素名称
					}else{
						//文件数据
						String name=fileItem.getName();				//文件名	a.txt
						String contentType=fileItem.getContentType();	//text	文件类型
						InputStream i=fileItem.getInputStream();	//文件流	上传文件流
						
						//处理输入流，将文件写入到服务器中
						//四、文件名重名
						String id=UUID.randomUUID().toString();
						name=id+"#"+name;
						//获取上传路径
						String path=getServletContext().getRealPath("/upload");
						System.out.println(path);
						File file=new File(path,name);
						if(!file.exists()){
							file.createNewFile();
						}
						fileItem.write(file);
						fileItem.delete();	//删除系统临时文件
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req, resp);
	}
}
